#include "iterator.h"

namespace minidb
{

Iterator::Iterator()
{
    cleanup_head_.func_ = nullptr;
    cleanup_head_.next_ = nullptr;
}

Iterator::~Iterator()
{
    if (!cleanup_head_.IsEmpty())
    {
        cleanup_head_.Run();
        for (CleanupNode *node = cleanup_head_.next_; node != nullptr;)
        {
            node->Run();
            CleanupNode *next_node = node->next_;
            delete node;
            node = next_node;
        }
    }
}

void Iterator::RegisterCleanup(CleanupFunction function, void *arg1, void *arg2)
{
    assert(function != nullptr);
    CleanupNode *node;
    if (cleanup_head_.IsEmpty())
    {
        node = &cleanup_head_;
    }
    else
    {
        node = new CleanupNode();
        node->next_ = cleanup_head_.next_;
        cleanup_head_.next_ = node;
    }
    node->func_ = function;
    node->arg1_ = arg1;
    node->arg2_ = arg2;
}

class EmptyIterator : public Iterator
{
public:
    EmptyIterator(const Status &s) :
        status_(s)
    {
    }

    virtual bool Vaild() const override
    {
        return false;
    };

    virtual void SeekToFirst() override {};

    virtual void SeekToLast() override {};

    virtual void Seek(const Slice &target) override {};

    virtual void Next() override
    {
        assert(false);
    };

    virtual void Prev() override
    {
        assert(false);
    };

    virtual Slice key() const override
    {
        assert(false);
        return Slice();
    };

    virtual Slice value() const
    {
        assert(false);
        return Slice();
    };

    virtual Status status() const override
    {
        return status_;
    };

    ~EmptyIterator() override = default;

private:
    Status status_;
};

/// @brief 获取空迭代器
/// @return 
Iterator *NewEmptyIterator()
{
    return new EmptyIterator(Status::OK());
}

/// @brief 根据传入的status获取错误迭代器
/// @param status 
/// @return 
Iterator *NewErrorIterator(const Status &status)
{
    return new EmptyIterator(status);
}

} // namespace minidb